<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\api\home;

use think\Controller;
use think\exception\HttpResponseException;
use think\facade\Cache;
use think\facade\Request;
use think\Response;
use function GuzzleHttp\json_decode;
use think\Db;
use think\Image;
use think\File;
use app\api\home\WxBizDataCrypt;

use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory;





/**
 * 前台首页控制器
 * @package app\index\controller
 */
// 指定允许其他域名访问
header('Access-Control-Allow-Origin:*');
// 响应类型
header('Access-Control-Allow-Methods:*');
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with,content-type');
class Alipay extends Controller
{
    protected $responseType = 'json';
    protected $pageSize = 10;
    protected $url = 'http://app.ssxzs.cn/';
    protected $config = [
        'appId'             => '2021002180682580',
        'ali_public_key'             => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAou3BLDox2YxvDQXiR8Z/wiC3uufVAnJxX7kNdkJQiYICjNsp8gYdmsH/mni/s/jpGQoMrH3fiz7nY0pr4isgaBuw3BT10y788VE2h4pd4VzsAFG9KrNLOd++9sVWuuVTmNpxKELMeWUZE1g/l1OSP8cZJWaVrtDMxeT493MNZO3mW9LZLuWhhSgQRmM1IK3xjAniWUh3ATpUu5qhcjCGfKzLwdhZ79qlvzrZB7rT69H91zUxQQPZS8ihoytphRVmOnohnIYONrgs+nCnmEGk4puJYL8EE0b5XTG8jFYlSCQQUPYkFJS2z3sv7DMRewe7XDlw0a/jx1acxcrSUSPpFwIDAQAB',
        'ali_private_key'                => 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCovaUpeTTPVif9MSg96P/e+K97Gjn2H6SSdk8Wv89baScKGFho+Q6Y8Le0KbprjOa8dy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UwiHcbBQ5Z02w0eUYl+X7gEv0txVirGS72OcScYNITWQJ4v3mmb4TDYkSVLMDlBxPMY+njUuAQKBgBbBcwswWMvbBHt0Lbze3RtYiGj4vQ0QrcxC77G9FJX1XUfA5uvCPQQXPI03yWC3cJ8klkOk1pjtfKePGBmSXU5yo05Gb2IkS2rCFy5cYUzKe4OW4D0rr4nIMAGNfa/QUe/OPXpdk04gdqfWzOdLBt+7XhKXNiLFD4IpyRaxLCvRAoGBAK97a/MyP4pmEPB8Bo8tWeRuKeWNscMNB7EWSGAIccd/QK8c+SdsHlxKK3ULNqRlE6bkztC0jpVb6C952SqiDP+Jeae6vsMHfjRQsfF6Z0NrQEAbKq1+Bs5Vl9QJKPYkZgy4kFwwAGaeNiklkHTx+VPxVPeWKbov4ditptxMe9JP',   // API 密钥
        
    ];
    
    
    /**
     * 操作成功返回的数据
     * @param string $msg   提示信息
     * @param mixed $data   要返回的数据
     * @param int   $code   错误码，默认为1
     * @param string $type  输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function success($data = null,$code = 200,$msg = '',$type = null, array $header = [],$ret=null)
    {
        $this->result($data, $code, $msg, $type, $header,$ret);
    }
    
    /**
     * 操作失败返回的数据
     * @param string $msg   提示信息
     * @param mixed $data   要返回的数据
     * @param int   $code   错误码，默认为0
     * @param string $type  输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function error($data = null, $code = 0,$msg = '',$type = null, array $header = [])
    {
        $this->result($data,$code,$msg,$type, $header);
    }
    
    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   要返回的数据
     * @param int    $code   错误码，默认为0
     * @param string $type   输出类型，支持json/xml/jsonp
     * @param array  $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($data, $code = 0,$msg = '', $type = '', array $header = [],$ret=null)
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
            'ret' => $ret,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : (\request()->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
        
        if (isset($header['statuscode']))
        {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        }
        else
        {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    public function pay(){
        
        $d=$this->request->param();
        
        
        
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->appId = "2021002180682580";
        $options->signType = 'RSA2';
        $options->alipayPublicKey = $this->config['ali_public_key'];
        $options->merchantPrivateKey = $this->config['ali_private_key'];
        $options->notifyUrl = "http://app.ssxzs.cn/api/alipay/callback";
        Factory::setOptions($options);
        $date=date("Y-m-d H:i:s");
        
        
        
        $types=$d['type'];
        $t="ls_".$types;
        
        $arr=[
            "dianhuazixun",
            "lvshihan",
            "tuwen",
            "wenshu",
            "yuyue",
        ];
        if(in_array($types, $arr)){
            $lvshi_id=Db::name($t)->where("id",$d['product_id'])->value("lvshi_id");
        }else{
            $lvshi_id=0;
        }
        
        
        // 计算产品总价格及支付详情
        $totalPrice=$d['price'];
        $orderTitle = '加油卡费用';
        $orderDetail = "阿里支付";
        
        
        $userId = isset($d["user_id"])?$d["user_id"]:0;
            //构造统一订单接口参数
            $out_trade_no = time() . rand(1000, 9999).rand(1000,9999);//订单号
            
            
            
            $order_id=Db::name("order")->insertGetId([
                'user_id'           => $d['user_id'],
                'out_trade_no'      => $out_trade_no,
                'total_fee'         => $totalPrice*100,
                'status'            => 0,
                'body'           => '费用支付',
                'detail'           => '费用支付',
                'create_time'           => $date,
                'update_time'           => $date,
                'type'           => $d['type'],
                'product_id'           => $d['product_id'],
                'lvshi_id'        => $lvshi_id,
            ]);
            
            
            
            if (isset($d['huabe']) and $d['huabei'])
            {
                $result = Factory::payment()
                ->app()
                ->optional("extend_params",$this->getHuabeiParams()) // 花呗配置
                ->pay($orderTitle,$out_trade_no,$totalPrice);
            }
            else
            {
 
                $result = Factory::payment()
                ->app()
                ->pay($orderTitle,$out_trade_no,$totalPrice);
            }
            
            $datas=[
                "order_id"=>$order_id,
                "result"=>$result->body,
                "out_trade_no"  => $out_trade_no,
            ];
            
            return $this->success($datas);
           // $this->success($result->body);
        
    }
    
    private function getHuabeiParams()
    {
        $extendParams = array(
            "hb_fq_num" => "12", // 分期数
            "hb_fq_seller_percent" => "0" // 卖家分期手续费百分比
        );
        return $extendParams;
    }
    /**
     * @ int article_id
     * @Route("callback", method="POST")
     * 支付回调
     */
    public function callback(){
        
        $message = \request()->param();
        
        // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
        $order = Db::name("order")->where(['out_trade_no'=>$message['out_trade_no']])->find();
        
        if (empty($order) || $order['status']==1) { // 如果订单不存在 或者 订单已经支付过了
            return 1;
        }
        
        // 用户是否支付成功
        if ($message['trade_status'] === 'TRADE_SUCCESS') {
            
            Db::name("order")->where("id",$order['id'])->update([
                "status"=>1,
                "pay_status"=>1,
                "pay_type"=>"支付宝支付",
                "pay_time"=>date("Y-m-d H:i:s",time()),
                "update_time"=>date("Y-m-d H:i:s",time()),
            ]);
            $total_fee=$order['total_fee']/100;
            $recommend_id=Db::name("user")->where("id",$order['user_id'])->value("recommend_id");
            if($recommend_id){  //推荐人
                $total_fee1=$total_fee/10;
                Db::name("user")->where(['id'=>$recommend_id])->setInc('point',$total_fee1);
                //写入记录
                Db::name("point_log")->insert([
                    "point"=>$total_fee1,
                    "user_id"=>$recommend_id,
                    "remarks"=>"分销分成",
                    "type"=>1,
                    "create_time"=>date("Y-m-d H:i:s"),
                    "link_user_id"=>$order['user_id'],
                ]);
                
                
                $total_fee2=$total_fee-$total_fee1;
                Db::name("user")->where(['id'=>$order['lvshi_id']])->setInc('point',$total_fee2);
                //写入记录
                Db::name("point_log")->insert([
                    "point"=>$total_fee2,
                    "user_id"=>$order['lvshi_id'],
                    "remarks"=>"加油卡收益",
                    "type"=>1,
                    "create_time"=>date("Y-m-d H:i:s"),
                    "link_user_id"=>$order['user_id'],
                ]);
                
                
            }else{
                
                Db::name("user")->where(['id'=>$order['lvshi_id']])->setInc('point',$total_fee);
                //写入记录
                Db::name("point_log")->insert([
                    "point"=>$total_fee,
                    "user_id"=>$order['lvshi_id'],
                    "remarks"=>"加油卡收益",
                    "type"=>1,
                    "create_time"=>date("Y-m-d H:i:s"),
                    "link_user_id"=>$order['user_id'],
                ]);
            }
            
            return true;
                
                // 用户支付失败
        } elseif ($message['return_code'] === 'FAIL') {
            $order->status = 0;
            $order->save();
        }
        return 1;
    }
    
    
    
}
